<template>
  <el-dialog
      fullscreen
      top="5vh"
      width="1400px"
      title="线路管理"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <div class="sku-container">
      <div class="product-info">
        <h3>{{ currentProduct.name }}</h3>
        <p>商品ID: {{ currentProduct.id }}</p>
      </div>

      <!-- 规格配置区域 -->
      <el-card class="spec-config" shadow="never">
        <div slot="header" class="clearfix">
          <span>规格配置</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="onAddSpec">添加规格</el-button>
        </div>

        <div class="spec-list">
          <div v-for="(spec, specIndex) in specList" :key="spec.id" class="spec-item">
            <div class="spec-header">
              <el-input
                v-model="spec.spec_name"
                placeholder="规格名称，如：颜色、尺寸"
                style="width: 200px; margin-right: 10px;"
              />
              <el-button type="text" @click="addSpecValue(specIndex)">添加规格值</el-button>
              <el-button type="text" style="color: #F82222" @click="removeSpec(specIndex)">删除规格</el-button>
            </div>
            <div class="spec-values">
              <el-tag
                v-for="(value, valueIndex) in spec.spec_values"
                :key="valueIndex"
                closable
                @close="removeSpecValue(specIndex, valueIndex)"
                style="margin-right: 10px; margin-bottom: 10px;"
              >
                {{ value }}
              </el-tag>
            </div>
          </div>
        </div>

        <div class="spec-actions" v-if="specList.length > 0">
          <el-button type="primary" @click="saveSpecs">保存规格配置</el-button>
          <!-- <el-button @click="generateSkuCombinations">生成线路组合</el-button> -->
        </div>
      </el-card>

      <!-- 线路管理区域 -->
      <el-card class="sku-manager" shadow="never">
        <div slot="header" class="clearfix">
          <span>线路管理</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="onAddSku">新增线路</el-button>
        </div>

        <div class="sku-table">
          <el-table
              size="large"
              stripe
              border
              v-loading="loading"
              :data="skuList"
              row-key="id"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.8)"
          >
            
            <el-table-column prop="sku_code" label="线路编码" width="150"/>
            <el-table-column prop="image" label="线路图片" width="120">
              <template slot-scope="scope">
                <el-image
                    v-if="scope.row.image"
                    :preview-src-list="[scope.row.image]"
                    style="width: 80px; height: 80px"
                    :src="scope.row.image" fit="contain">
                  <template #error>
                    <img src="@/assets/file.png" alt="" style="width: 80px; height: 80px">
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="spec_combination" label="规格组合" min-width="200">
              <template slot-scope="scope">
                <div v-if="scope.row.spec_combination">
                  <el-tag
                    v-for="(value, key) in JSON.parse(scope.row.spec_combination)"
                    :key="key"
                    size="mini"
                    style="margin-right: 5px; margin-bottom: 5px;"
                  >
                    {{ key }}: {{ value }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="adult_price" label="成人价格" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.adult_price }}
              </template>
            </el-table-column>
            <el-table-column prop="child_price" label="儿童价格" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.child_price }}
              </template>
            </el-table-column> -->
            <el-table-column prop="share_price" label="成人佣金" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.share_price }}
              </template>
            </el-table-column>
            <el-table-column prop="share_price2" label="儿童佣金" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.share_price2 }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
                <el-tag v-else type="info">禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="200">
              <template slot-scope="scope">
                <el-button type="text" @click="onEditSku(scope.row)">编辑</el-button>
                <el-button type="text" @click="onManageStock(scope.row)">团期管理</el-button>
                <el-button type="text" style="color: #F82222" @click="onDeleteSku(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>

    <!-- 规格值输入弹窗 -->
    <el-dialog
        title="添加规格值"
        :visible.sync="specValueDialog"
        width="400px"
        append-to-body
    >
      <el-input
        v-model="newSpecValue"
        placeholder="请输入规格值"
        @keyup.enter.native="confirmAddSpecValue"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="specValueDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAddSpecValue">确定</el-button>
      </div>
    </el-dialog>

    <!-- SKU添加/编辑弹窗 -->
    <el-dialog
        top="10vh"
        width="800px"
        title="添加/编辑线路"
        :visible.sync="skuDialogValue"
        :close-on-click-modal="false"
        append-to-body
    >
      <SubmitForm
          :rule-form="skuForm"
          :rules="skuRules"
          :form-list="skuFormList"
          @change="handleSkuFormChange"
          @save="onSaveSku"
          @close="skuDialogValue = false"
      >
        <!-- 自定义规格选择组件 -->
        <template slot="spec_combination">
          <SpecCombinationSelector
            ref="specSelector"
            v-model="skuForm.spec_combination"
            :spec-list="specList"
            @change="handleSpecCombinationChange"
          />
        </template>
      </SubmitForm>
    </el-dialog>

    <!-- 团期管理弹窗 -->
    <el-dialog
        fullscreen
        top="5vh"
        width="1400px"
        title="团期管理"
        :visible.sync="stockDialogValue"
        :close-on-click-modal="false"
        append-to-body
    >
      <div class="stock-container">
        <div class="sku-info">
          <h3>{{ getFormatSkuSpec(currentSku) }}</h3>
        </div>

        <div class="stock-actions">
          <el-button type="primary" :loading="addStockLoading" @click="onAddStock">新增团期</el-button>
          <el-button @click="batchAddStock">批量添加</el-button>
          <el-button type="danger" :loading="deleteStockLoading" :disabled="!selectedStockItems?.length" @click="batchDeleteStock">批量删除</el-button>
        </div>

        <div class="stock-table">
          <el-table
              size="large"
              stripe
              border
              v-loading="stockLoading"
              :data="stockList"
              row-key="id"
              @selection-change="handleSelectionChange"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.8)"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="travel_date" label="销售日期" width="120">
              <template slot-scope="scope">
                {{ formatDate(scope.row.travel_date) }}
              </template>
            </el-table-column>
            <el-table-column prop="adult_price" label="成人价格" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.adult_price }}
              </template>
            </el-table-column>
            <el-table-column prop="child_price" label="儿童价格" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.child_price }}
              </template>
            </el-table-column>
            <el-table-column prop="single_price_diff" label="单房差" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.single_price_diff }}
              </template>
            </el-table-column>
            <el-table-column prop="adult_available_stock" label="可售人数" width="100">
              <template slot-scope="scope">
                {{ scope.row.adult_available_stock }}/{{ scope.row.adult_total_stock }}
              </template>
            </el-table-column>
            <el-table-column prop="is_group" label="是否拼团" width="80">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.is_group === 1" type="success">是</el-tag>
                <el-tag v-else type="info">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="group_adult_price" label="拼团成人价" width="120">
              <template slot-scope="scope">
                <span v-if="scope.row.is_group === 1">¥{{ scope.row.group_adult_price }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="group_child_price" label="拼团儿童价" width="120">
              <template slot-scope="scope">
                <span v-if="scope.row.is_group === 1">¥{{ scope.row.group_child_price }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="group_adult_people" label="拼团人数" width="120">
              <template slot-scope="scope">
                <span v-if="scope.row.is_group === 1">{{ scope.row.group_adult_people }}人</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 1" type="success">上架</el-tag>
                <el-tag v-else type="info">下架</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
              <template slot-scope="scope">
                <el-button type="text" @click="onEditStock(scope.row)">编辑</el-button>
                <el-button type="text" :loading="scope.row.deleteLoading" style="color: #F82222" @click="onDeleteStock(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 团期添加/编辑弹窗 -->
    <el-dialog
        top="10vh"
        width="800px"
        title="添加/编辑团期"
        :visible.sync="stockFormDialog"
        :close-on-click-modal="false"
        append-to-body
    >
      <SubmitForm
          :loading="addStockLoading"
          :rule-form="stockForm"
          :rules="stockRules"
          :form-list="stockFormList"
          @change="handleStockFormChange"
          @save="onSaveStock"
          @close="stockFormDialog = false"
      >
        <template slot="hotel_levels">
          <div class="hotel-levels-container">
            <div class="hotel-levels-header">
              <h4>酒店级别配置（默认获取旅游产品酒店级别配置）</h4>
              <el-button type="primary" size="small" @click="addStockHotelLevel">
                <i class="el-icon-plus"></i> 添加级别
              </el-button>
            </div>
            <div class="hotel-levels-list">
              <el-table :data="stockForm.hotel_levels" border style="width: 100%">
                <el-table-column prop="level_name" label="级别名称" width="200">
                  <template slot-scope="scope">
                    <el-input 
                      v-model="scope.row.level_name" 
                      placeholder="请输入级别名称"
                      size="small">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="价格" width="200">
                  <template slot-scope="scope">
                    <el-input-number 
                      v-model="scope.row.price" 
                      :precision="2" 
                      :step="0.01" 
                      :min="0"
                      size="small"
                      placeholder="请输入价格">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" min-width="200">
                  <template slot-scope="scope">
                    <el-input 
                      v-model="scope.row.description" 
                      placeholder="请输入级别描述"
                      size="small">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="single_diff" label="单房差" width="150">
                  <template slot-scope="scope">
                    <el-input-number 
                      v-model="scope.row.single_diff" 
                      :precision="2" 
                      :step="0.01" 
                      :min="0"
                      size="small"
                      placeholder="单人间差价">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="排序" width="120">
                  <template slot-scope="scope">
                    <el-input-number 
                      v-model="scope.row.sort" 
                      :min="0"
                      :step="1"
                      size="small"
                      placeholder="排序值"
                      @change="onStockSortChange">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template slot-scope="scope">
                    <el-button 
                      type="danger" 
                      size="mini" 
                      @click="removeStockHotelLevel(scope.$index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div v-if="stockForm.hotel_levels.length === 0" class="empty-tip">
                <p>暂无酒店级别配置，请点击"添加级别"按钮进行配置</p>
              </div>
            </div>
          </div>
        </template>
      </SubmitForm>
    </el-dialog>

    <!-- 批量添加团期弹窗 -->
    <el-dialog
        top="10vh"
        width="1000px"
        title="批量添加团期"
        :visible.sync="batchStockDialog"
        :close-on-click-modal="false"
        append-to-body
    >
      <el-form :model="batchForm" :rules="batchRules" ref="batchFormRef" label-width="120px">
        <el-form-item label="开始日期" prop="start_date">
          <el-date-picker
            v-model="batchForm.start_date"
            type="date"
            placeholder="选择开始日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="end_date">
          <el-date-picker
            v-model="batchForm.end_date"
            type="date"
            placeholder="选择结束日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="成人价格" prop="adult_price">
          <el-input-number
            v-model="batchForm.adult_price"
            :precision="2"
            :step="0.01"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="儿童价格" prop="child_price">
          <el-input-number
            v-model="batchForm.child_price"
            :precision="2"
            :step="0.01"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="单房差价格" prop="single_price_diff">
          <el-input-number
            v-model="batchForm.single_price_diff"
            :precision="2"
            :step="0.01"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="可售人数" prop="adult_stock">
          <el-input-number
            v-model="batchForm.adult_stock"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="是否拼团" prop="is_group">
          <el-switch
            v-model="batchForm.is_group"
            active-value="1"
            inactive-value="0"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        <el-form-item label="拼团成人价格" prop="group_adult_price" v-if="batchForm.is_group === '1'">
          <el-input-number
            v-model="batchForm.group_adult_price"
            :precision="2"
            :step="0.01"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="拼团儿童价格" prop="group_child_price" v-if="batchForm.is_group === '1'">
          <el-input-number
            v-model="batchForm.group_child_price"
            :precision="2"
            :step="0.01"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="拼团人数" prop="group_adult_people" v-if="batchForm.is_group === '1'">
          <el-input-number
            v-model="batchForm.group_adult_people"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
        
        <!-- 酒店级别配置 -->
        <el-form-item label="酒店级别" prop="hotel_levels">
          <div class="hotel-levels-container">
            <div class="hotel-levels-header">
              <h4>酒店级别配置（默认获取旅游产品酒店级别配置）</h4>
              <el-button type="primary" size="small" @click="addBatchHotelLevel">
                <i class="el-icon-plus"></i> 添加级别
              </el-button>
            </div>
            <div class="hotel-levels-list">
              <el-table :data="batchForm.hotel_levels" border style="width: 100%">
                <el-table-column prop="level_name" label="级别名称" width="200">
                  <template slot-scope="scope">
                    <el-input 
                      v-model="scope.row.level_name" 
                      placeholder="请输入级别名称"
                      size="small">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="价格" width="200">
                  <template slot-scope="scope">
                    <el-input-number 
                      v-model="scope.row.price" 
                      :precision="2" 
                      :step="0.01" 
                      :min="0"
                      size="small"
                      placeholder="请输入价格">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" min-width="200">
                  <template slot-scope="scope">
                    <el-input 
                      v-model="scope.row.description" 
                      placeholder="请输入级别描述"
                      size="small">
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="single_diff" label="单房差" width="150">
                  <template slot-scope="scope">
                    <el-input-number 
                      v-model="scope.row.single_diff" 
                      :precision="2" 
                      :step="0.01" 
                      :min="0"
                      size="small"
                      placeholder="单人间差价">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="排序" width="120">
                  <template slot-scope="scope">
                    <el-input-number 
                      v-model="scope.row.sort" 
                      :min="0"
                      :step="1"
                      size="small"
                      placeholder="排序值"
                      @change="onBatchSortChange">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120">
                  <template slot-scope="scope">
                    <el-button 
                      type="danger" 
                      size="mini" 
                      @click="removeBatchHotelLevel(scope.$index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div v-if="batchForm.hotel_levels.length === 0" class="empty-tip">
                <p>暂无酒店级别配置，请点击"添加级别"按钮进行配置</p>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchStockDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchAdd">确定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {http} from '@/api'
import SpecCombinationSelector from '@/components/SpecCombinationSelector.vue'

export default {
  name: 'SkuManager',
  components: {
    SpecCombinationSelector
  },
  data() {
    return {
      dialogValue: false,
      skuDialogValue: false,
      specValueDialog: false,
      stockDialogValue: false,
      stockFormDialog: false,
      batchStockDialog: false,
      loading: false,
      stockLoading: false,
      currentProduct: {},
      currentSku: {},
      skuList: [],
      specList: [],
      stockList: [],
      selectedStockItems: [], // 选中的团期列表
      addStockLoading: false, // 新增团期按钮loading
      deleteStockLoading: false, // 删除团期按钮loading
      skuForm: {},
      stockForm: {
        hotel_levels: []
      },
      batchForm: {
        hotel_levels: []
      },
      newSpecValue: '',
      currentSpecIndex: -1,
      defaultSkuForm: {
        travel_id: '',
        sku_code: '',
        spec_combination: '{}',
        adult_price: 0,
        child_price: 0,
        adult_original_price: 0,
        child_original_price: 0,
        share_price: 0,
        share_price2: 0,
        stock: 0,
        image: '',
        unit: '',
        status: 1
      },
      defaultStockForm: {
        travel_sku_id: '',
        travel_date: '',
        adult_price: 0,
        child_price: 0,
        adult_original_price: 0,
        child_original_price: 0,
        single_price_diff: 0,
        adult_total_stock: 0,
        child_total_stock: 0,
        is_group: 0,
        group_adult_price: 0,
        group_child_price: 0,
        group_adult_people: 0,
        group_child_people: 0,
        status: 1,
        hotel_levels: [] // 酒店级别列表
      },
      defaultBatchForm: {
        start_date: '',
        end_date: '',
        adult_price: 0,
        child_price: 0,
        single_price_diff: 0,
        adult_stock: 0,
        child_stock: 0,
        is_group: '0',
        group_adult_price: 0,
        group_child_price: 0,
        group_adult_people: 0,
        group_child_people: 0,
        hotel_levels: [] // 酒店级别列表
      },
      skuRules: {
        spec_combination: [
          {
            required: true,
            message: '线路规格不能为空'
          }
        ]
      },
      stockRules: {
        travel_date: [{required: true, message: '销售日期不能为空'}],
      },
      batchRules: {
        start_date: [{required: true, message: '开始日期不能为空'}],
        end_date: [{required: true, message: '结束日期不能为空'}],
      },
      skuFormList: [
        {
          label: '线路编码',
          prop: 'sku_code',
          name: 'input',
          colSpan: 24,
          placeholder: '请输入线路编码'
        },
        {
          label: '线路图片',
          prop: 'image',
          name: 'file',
          colSpan: 24
        },
        {
          label: '线路规格',
          prop: 'spec_combination',
          slot: true,
          colSpan: 24
        },
        // {
        //   label: '成人价格',
        //   prop: 'adult_price',
        //   name: 'number',
        //   colSpan: 8,
        //   min: 0,
        //   precision: 2,
        //   step: 0.01
        // },
        // {
        //   label: '儿童价格',
        //   prop: 'child_price',
        //   name: 'number',
        //   colSpan: 8,
        //   min: 0,
        //   precision: 2,
        //   step: 0.01
        // },
        {
          label: '成人佣金',
          prop: 'share_price',
          name: 'number',
          colSpan: 24,
          min: 0,
          precision: 2,
          step: 0.01
        },
        {
          label: '儿童佣金',
          prop: 'share_price2',
          name: 'number',
          colSpan: 24,
          min: 0,
          precision: 2,
          step: 0.01
        },
        {
          label: '状态',
          prop: 'status',
          name: 'switch',
          colSpan: 24,
          activeValue: 1,
          inactiveValue: 0,
          activeText: '启用',
          inactiveText: '禁用'
        },
      ],
      stockFormList: [
        {
          label: '销售日期',
          prop: 'travel_date',
          name: 'datetime',
          colSpan: 24,
          dateType: 'date',
          valueFormat: 'yyyy-MM-dd'
        },
        {
          label: '成人价格',
          prop: 'adult_price',
          name: 'number',
          colSpan: 12,
          min: 0,
          precision: 2,
          step: 0.01
        },
        {
          label: '儿童价格',
          prop: 'child_price',
          name: 'number',
          colSpan: 12,
          min: 0,
          precision: 2,
          step: 0.01
        },
        // {
        //   label: '成人原价',
        //   prop: 'adult_original_price',
        //   name: 'number',
        //   colSpan: 12,
        //   min: 0,
        //   precision: 2,
        //   step: 0.01
        // },
        // {
        //   label: '儿童原价',
        //   prop: 'child_original_price',
        //   name: 'number',
        //   colSpan: 12,
        //   min: 0,
        //   precision: 2,
        //   step: 0.01
        // },
        {
          label: '可售人数',
          prop: 'adult_total_stock',
          name: 'number',
          colSpan: 12,
          min: 0
        },
        {
          label: '单房差价格',
          prop: 'single_price_diff',
          name: 'number',
          colSpan: 12,
          min: 0,
          precision: 2,
          step: 0.01
        },
        {
          label: '是否拼团',
          prop: 'is_group',
          name: 'switch',
          colSpan: 12,
          activeValue: 1,
          inactiveValue: 0,
          activeText: '是',
          inactiveText: '否'
        },
        {
          label: '拼团人数',
          prop: 'group_adult_people',
          name: 'number',
          colSpan: 12,
          min: 1,
          show: () => this.stockForm.is_group == '1'
        },
        {
          label: '状态',
          prop: 'status',
          name: 'switch',
          colSpan: 24,
          activeValue: 1,
          inactiveValue: 0,
          activeText: '上架',
          inactiveText: '下架'
        },
        {
          label: '酒店级别',
          prop: 'hotel_levels',
          slot: true,
          colSpan: 24
        }
      ]
    }
  },
  methods: {
    open(product) {
      this.currentProduct = product;
      this.dialogValue = true;
      this.loadSpecList();
      this.loadSkuList();
    },

    // 加载规格列表
    loadSpecList() {
      http.travelSpec.list({ travel_id: this.currentProduct.id }).then(res => {
        this.specList = res.data.map(spec => ({
          ...spec,
          spec_values: spec.spec_values ? JSON.parse(spec.spec_values) : []
        }));
      }).catch(() => {
        this.specList = [];
      });
    },

    // 加载SKU列表
    loadSkuList() {
      this.loading = true;
      http.travelSku.list({ travel_id: this.currentProduct.id }).then(res => {
        this.skuList = res.data;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    // 添加规格
    onAddSpec() {
      this.specList.push({
        travel_id: this.currentProduct.id,
        spec_name: '',
        spec_values: [],
        sort: this.specList.length,
        status: 1
      });
    },

    // 删除规格
    removeSpec(index) {
      this.specList.splice(index, 1);
    },

    // 添加规格值
    addSpecValue(specIndex) {
      this.currentSpecIndex = specIndex;
      this.newSpecValue = '';
      this.specValueDialog = true;
    },

    // 确认添加规格值
    confirmAddSpecValue() {
      if (this.newSpecValue.trim()) {
        this.specList[this.currentSpecIndex].spec_values.push(this.newSpecValue.trim());
        this.specValueDialog = false;
      }
    },

    // 删除规格值
    removeSpecValue(specIndex, valueIndex) {
      this.specList[specIndex].spec_values.splice(valueIndex, 1);
    },

    // 保存规格配置
    saveSpecs() {
      const specsToSave = this.specList.filter(spec => spec.spec_name.trim());

      if (specsToSave.length === 0) {
        this.$message.warning('请至少添加一个规格');
        return;
      }

      const promises = specsToSave.map(spec => {
        const specData = {
          ...spec,
          spec_values: JSON.stringify(spec.spec_values)
        };

        if (spec.id) {
          return http.travelSpec.update(spec.id, specData);
        } else {
          return http.travelSpec.create(null, specData);
        }
      });

      Promise.all(promises).then(() => {
        this.$message.success('规格配置保存成功');
        this.loadSpecList();
      })
    },

    // 生成线路组合
    generateSkuCombinations() {
      const validSpecs = this.specList.filter(spec => spec.spec_name.trim() && spec.spec_values.length > 0);

      if (validSpecs.length === 0) {
        this.$message.warning('请先配置规格');
        return;
      }

      // 调用后端接口生成线路组合
      http.travelSku.generate({ travel_id: this.currentProduct.id }).then(res => {
        this.$message.success(res.data.message);
        this.loadSkuList();
      })
    },

    // 生成规格组合
    generateCombinations(specs) {
      const result = [];

      const generate = (current, index) => {
        if (index === specs.length) {
          result.push([...current]);
          return;
        }

        for (const value of specs[index].spec_values) {
          current[index] = value;
          generate(current, index + 1);
        }
      };

      generate(new Array(specs.length), 0);
      return result;
    },

    // 生成线路编码
    generateSkuCode(combination) {
      return `${this.currentProduct.id}_${combination.join('_')}`;
    },

    onAddSku() {
      this.skuForm = {
        ...this.defaultSkuForm,
        travel_id: this.currentProduct.id
      };
      // 更新规格组合选择器的规格列表
      this.updateSpecCombinationProps();
      this.skuDialogValue = true;
    },

    onEditSku(row) {
      this.skuForm = { ...row };
      console.log('编辑SKU，规格组合:', this.skuForm.spec_combination);
      // 更新规格组合选择器的规格列表
      this.updateSpecCombinationProps();
      this.skuDialogValue = true;

      // 确保组件有时间响应数据变化
      this.$nextTick(() => {
        console.log('SKU表单已设置，当前规格组合:', this.skuForm.spec_combination);
      });
    },

    onDeleteSku(row) {
      this.$confirm('确定要删除这个SKU吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.travelSku.delete(row.id).then(() => {
          this.$message.success('删除成功');
          this.loadSkuList();
        });
      });
    },

    handleSkuFormChange({key, val}) {
      // 处理SKU表单变化
    },

    updateSpecCombinationProps() {
      // 规格列表已经在data中，不需要额外更新
      // 这个方法保留用于将来可能的扩展
    },

    handleSpecCombinationChange(combination) {
      // 处理规格组合变化
      console.log('规格组合变化:', combination);
    },

        onSaveSku() {
      // 验证规格组合JSON格式
      try {
        if (this.skuForm.spec_combination) {
          const parsed = JSON.parse(this.skuForm.spec_combination);
          // 检查是否选择了规格
          if (Object.keys(parsed).length === 0) {
            this.$message.warning('请选择规格组合');
            return;
          }
        }
      } catch (e) {
        this.$message.error('规格组合JSON格式不正确');
        return;
      }

      http.travelSku[this.skuForm.id ? 'update' : 'create'](this.skuForm.id, this.skuForm).then(res => {
        this.$message.success('操作成功');
        this.skuDialogValue = false;
        this.loadSkuList();
      });
    },

    onManageStock(row) {
      this.currentSku = row;
      this.stockDialogValue = true;
      this.loadStockList();
    },

    loadStockList() {
      this.stockLoading = true;
      http.travelSkuStock.list({ travel_sku_id: this.currentSku.id }).then(res => {
        // 处理每个团期的酒店级别数据
        this.stockList = res.data.map(stock => {
          if (stock.hotel_levels) {
            try {
              stock.hotel_levels = JSON.parse(stock.hotel_levels);
            } catch (error) {
              console.error('解析团期酒店级别配置失败:', error);
              stock.hotel_levels = [];
            }
          } else {
            stock.hotel_levels = [];
          }
          return stock;
        });
        this.stockLoading = false;
      }).catch(() => {
        this.stockLoading = false;
      });
    },
    getFormatSkuSpec() {
      let spec = this.currentSku?.spec_combination;
      if (!spec) return '';
      const spec_combination = JSON.parse(spec);
      let spec_name = '';
      for (const key in spec_combination) {
        spec_name += `${key}: ${spec_combination[key]} `;
      }
      return spec_name;
    },
    onAddStock() {
      this.stockForm = {
        ...this.defaultStockForm,
        travel_sku_id: this.currentSku.id
      };
      // 从旅游产品中载入酒店级别配置
      this.loadProductHotelLevels();
      this.stockFormDialog = true;
    },

    onEditStock(row) {
      this.stockForm = { ...row };
      
      // 处理酒店级别数据，如果是JSON字符串则转换为对象数组
      if (this.stockForm.hotel_levels && typeof this.stockForm.hotel_levels === 'string') {
        try {
          this.stockForm.hotel_levels = JSON.parse(this.stockForm.hotel_levels);
        } catch (error) {
          console.error('解析团期酒店级别配置失败:', error);
          this.stockForm.hotel_levels = [];
        }
      }
      
      // 如果编辑的团期没有酒店级别配置，则从旅游产品中载入
      if (!this.stockForm.hotel_levels || this.stockForm.hotel_levels.length === 0) {
        this.loadProductHotelLevels();
      }
      this.stockFormDialog = true;
    },

    // 从旅游产品中载入酒店级别配置
    loadProductHotelLevels() {
      // 通过currentProduct获取旅游产品的酒店级别配置
      if (this.currentProduct && this.currentProduct.hotel_levels) {
        try {
          let hotelLevels = [];
          if (typeof this.currentProduct.hotel_levels === 'string') {
            hotelLevels = JSON.parse(this.currentProduct.hotel_levels);
          } else {
            hotelLevels = this.currentProduct.hotel_levels;
          }
          
          if (Array.isArray(hotelLevels) && hotelLevels.length > 0) {
            this.stockForm.hotel_levels = hotelLevels.map(level => ({
              ...level,
              single_diff: level.single_diff || 0,
              sort: level.sort || 0
            }));
          } else {
            // 如果没有配置，提供默认的酒店级别选项
            this.stockForm.hotel_levels = [
              
            ];
          }
        } catch (error) {
          console.error('解析酒店级别配置失败:', error);
          // 解析失败时使用默认配置
          this.stockForm.hotel_levels = [
           
          ];
        }
      } else {
        // 如果旅游产品没有酒店级别配置，使用默认配置
        this.stockForm.hotel_levels = [
         
        ];
      }
    },

    onDeleteStock(row) {
      this.$confirm('确定要删除这个团期吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$set(row, 'deleteLoading', true);
        http.travelSkuStock.delete(row.id).then(() => {
          this.$message.success('删除成功');
          this.loadStockList();
        }).finally(() => {
          this.$set(row, 'deleteLoading', false);
        });
      });
    },

    handleStockFormChange({key, val}) {
      // 处理团期表单变化
    },

    onSaveStock() {
      // 验证酒店级别数据
      if (this.stockForm.hotel_levels && this.stockForm.hotel_levels.length > 0) {
        for (let i = 0; i < this.stockForm.hotel_levels.length; i++) {
          const level = this.stockForm.hotel_levels[i];
          if (!level.level_name || level.level_name.trim() === '') {
            this.$message.error(`第${i + 1}行酒店级别名称不能为空`);
            return;
          }
          if (level.price <= 0) {
            this.$message.error(`第${i + 1}行酒店级别价格必须大于0`);
            return;
          }
        }
      }

      this.addStockLoading = true;
      
      // 准备保存的数据，将酒店级别转换为JSON字符串
      const saveData = {
        ...this.stockForm,
        hotel_levels: JSON.stringify(this.stockForm.hotel_levels)
      };
      
      console.log('保存团期数据:', saveData);
      
      http.travelSkuStock[this.stockForm.id ? 'update' : 'create'](this.stockForm.id, saveData).then(res => {
        this.$message.success('操作成功');
        this.stockFormDialog = false;
        this.loadStockList();
      }).finally(() => {
        this.addStockLoading = false;
      });
    },

    batchAddStock() {
      this.batchForm = {
        ...this.defaultBatchForm,
        start_date: this.formatDate(new Date()),
        end_date: this.formatDate(new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)), // 默认30天
        hotel_levels: [] // 初始化酒店级别列表
      };
      
      // 从当前旅游产品加载酒店级别配置
      this.loadBatchProductHotelLevels();
      
      this.batchStockDialog = true;
    },

    confirmBatchAdd() {
      this.$refs.batchFormRef.validate(valid => {
        if (valid) {
          const startDate = this.formatDate(this.batchForm.start_date);
          const endDate = this.formatDate(this.batchForm.end_date);
          const dates = [];
          for (let d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
            dates.push(this.formatDate(d));
          }

          // 使用批量新增表单中的酒店级别配置
          let hotelLevels = this.batchForm.hotel_levels || [];
          
          // 验证酒店级别配置
          if (hotelLevels && hotelLevels.length > 0) {
            for (let i = 0; i < hotelLevels.length; i++) {
              const level = hotelLevels[i];
              if (!level.level_name || level.level_name.trim() === '') {
                this.$message.warning(`第${i + 1}个酒店级别的名称不能为空`);
                return;
              }
              if (!level.price || level.price <= 0) {
                this.$message.warning(`第${i + 1}个酒店级别的价格必须大于0`);
                return;
              }
            }
          }

          const promises = dates.map(date => {
            const stockData = {
              travel_sku_id: this.currentSku.id,
              travel_date: date,
              adult_price: this.batchForm.adult_price,
              child_price: this.batchForm.child_price,
              adult_total_stock: this.batchForm.adult_stock,
              child_total_stock: this.batchForm.child_stock,
              is_group: this.batchForm.is_group,
              group_adult_price: this.batchForm.group_adult_price,
              group_child_price: this.batchForm.group_child_price,
              group_adult_people: this.batchForm.group_adult_people,
              group_child_people: this.batchForm.group_child_people,
              single_price_diff: this.batchForm.single_price_diff,
              hotel_levels: JSON.stringify(hotelLevels), // 添加酒店级别配置
              status: 1
            };
            return http.travelSkuStock.create(null, stockData);
          });

          Promise.all(promises).then(() => {
            this.$message.success('批量添加成功');
            this.batchStockDialog = false;
            this.loadStockList();
          });
        }
      });
    },

    formatDate(date) {
      const d = new Date(date);
      let month = '' + (d.getMonth() + 1);
      let day = '' + d.getDate();
      const year = d.getFullYear();
      if (month.length < 2)
        month = '0' + month;
      if (day.length < 2)
        day = '0' + day;
      return [year, month, day].join('-');
    },
    handleSelectionChange(selection) {
      this.selectedStockItems = selection;
    },
    batchDeleteStock() {
      if (this.selectedStockItems.length === 0) {
        this.$message.warning('请选择要删除的团期');
        return;
      }
      this.$confirm(`确定要删除选中的 ${this.selectedStockItems.length} 个团期吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteStockLoading = true;
        const ids = this.selectedStockItems.map(item => item.id);
        http.travelSkuStock.batchDelete(ids).then(() => {
          this.$message.success('批量删除成功');
          this.loadStockList();
          this.selectedStockItems = []; // 清空选中
        }).finally(() => {
          this.deleteStockLoading = false;
        });
      });
    },

    addStockHotelLevel() {
      this.stockForm.hotel_levels.push({
        level_name: '',
        price: 0,
        description: '',
        single_diff: 0,
        sort: this.stockForm.hotel_levels.length
      });
    },

    removeStockHotelLevel(index) {
      this.$confirm(`确定要删除此酒店级别吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.stockForm.hotel_levels.splice(index, 1);
        // 重新排序剩余的酒店级别
        this.stockForm.hotel_levels.forEach((level, idx) => {
          level.sort = idx;
        });
      });
    },

    // 排序变化处理
    onStockSortChange() {
      // 根据sort字段重新排序酒店级别
      this.stockForm.hotel_levels.sort((a, b) => a.sort - b.sort);
    },

    // 从旅游产品加载酒店级别配置到批量新增表单
    loadBatchProductHotelLevels() {
      if (this.currentProduct && this.currentProduct.hotel_levels) {
        try {
          let hotelLevels = [];
          if (typeof this.currentProduct.hotel_levels === 'string') {
            hotelLevels = JSON.parse(this.currentProduct.hotel_levels);
          } else {
            hotelLevels = this.currentProduct.hotel_levels;
          }
          
          if (Array.isArray(hotelLevels) && hotelLevels.length > 0) {
            this.batchForm.hotel_levels = hotelLevels.map(level => ({
              level_name: level.level_name || '',
              price: level.price || 0,
              description: level.description || '',
              single_diff: level.single_diff || 0,
              sort: level.sort || 0
            }));
          } else {
            this.batchForm.hotel_levels = [];
          }
        } catch (error) {
          console.error('解析旅游产品酒店级别配置失败:', error);
          this.batchForm.hotel_levels = [];
        }
      } else {
        this.batchForm.hotel_levels = [];
      }
    },

    // 批量新增表单的酒店级别管理方法
    addBatchHotelLevel() {
      this.batchForm.hotel_levels.push({
        level_name: '',
        price: 0,
        description: '',
        single_diff: 0,
        sort: this.batchForm.hotel_levels.length
      });
    },

    removeBatchHotelLevel(index) {
      this.$confirm(`确定要删除此酒店级别吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.batchForm.hotel_levels.splice(index, 1);
        // 重新排序剩余的酒店级别
        this.batchForm.hotel_levels.forEach((level, idx) => {
          level.sort = idx;
        });
      });
    },

    // 批量新增表单排序变化处理
    onBatchSortChange() {
      // 根据sort字段重新排序酒店级别
      this.batchForm.hotel_levels.sort((a, b) => a.sort - b.sort);
    }
  }
}
</script>

<style scoped lang="scss">
.sku-container {
  .product-info {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;

    h3 {
      margin: 0 0 10px 0;
      color: #303133;
    }

    p {
      margin: 0;
      color: #606266;
    }
  }

  .spec-config {
    margin-bottom: 20px;

    .spec-list {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 20px;
      .spec-item {
        margin-bottom: 20px;
        padding: 15px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;

        .spec-header {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
        }

        .spec-values {
          min-height: 40px;
        }
      }
    }

    .spec-actions {
      margin-top: 20px;
      text-align: center;
    }
  }

  .sku-manager {
    .sku-table {
      max-height: 400px;
      overflow-y: auto;
    }
  }
}

.stock-container {
  .sku-info {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;

    h3 {
      margin: 0 0 10px 0;
      color: #303133;
    }

    p {
      margin: 0;
      color: #606266;
    }
  }

  .stock-actions {
    margin-bottom: 20px;
  }

  .stock-table {
    max-height: 500px;
    overflow-y: auto;
  }
}

.hotel-levels-container {
  .hotel-levels-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h4 {
      margin: 0;
      color: #303133;
      font-size: 16px;
      font-weight: 600;
    }
  }
  
  .hotel-levels-list {
    .el-table {
      .el-table__header {
        background-color: #f5f7fa;
        
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }
      
      .el-table__row {
        &:hover {
          background-color: #f5f7fa;
        }
      }
      
      .el-input,
      .el-input-number {
        .el-input__inner {
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          
          &:focus {
            border-color: #409eff;
          }
        }
      }
      
      .el-button--danger {
        padding: 5px 10px;
        font-size: 12px;
        
        &:hover {
          background-color: #f56c6c;
          border-color: #f56c6c;
        }
      }
      
      .el-button--text {
        padding: 5px;
        font-size: 14px;
        color: #409eff;
        
        &:hover:not(:disabled) {
          color: #66b1ff;
          background-color: #ecf5ff;
        }
        
        &:disabled {
          color: #c0c4cc;
          cursor: not-allowed;
        }
        
        i {
          font-size: 16px;
        }
      }
    }
    
    .empty-tip {
      text-align: center;
      color: #909399;
      padding: 40px 0;
      
      p {
        margin: 0;
        font-size: 14px;
      }
    }
  }
}
</style>
